<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
  <div id="container"></div>
  <script>

    d3.csv('data.csv').then((data) => {
      console.log(data)

      var sum = d3.sum(data.map((d)=>d.population));
      for(i in data){
        data[i].percentage= (data[i].population/sum * 100).toFixed(0) + '%'
      }


      var width = 800, height = 800, margin = 30;
      var colors = d3.schemeCategory10;


      var svg = d3.select("#container")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
      // .style("background", "#efefef")


      var arc_generator = d3.arc()
        .innerRadius(width / 8)
        .outerRadius(width / 4);

      //内环和外环公用
      var angle_data = d3.pie()
        .value(function (d) {
          return d.population;
        })
      console.log(angle_data(data))

      var Pie = svg.append('g').attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
      Pie.selectAll("path")
        .data(angle_data(data))
        .enter()
        .append("path")
        .attr("d", function (d, i) {
          console.log(arc_generator(d))
          return arc_generator(d);
        })
        .style('fill', function (d, i) {
          return colors[i]
        })

      //添加文字标注
      var arc_label = d3.arc()
        .innerRadius(width / 4)
        .outerRadius(width / 2)


      Pie.selectAll(".arc_label")
        .data(angle_data(data))
        .enter()
        .append("path")
        .attr('d', arc_label)
        .attr('class', '.arc_label')
        .style('fill', 'none')


      //绘制标注线
      function line_label(angle_data) {
        var str = "";
        var i = 0;
        for (let d in angle_data) {
          //外环的中心点
          str = "M" + arc_generator.centroid(angle_data[d])[0] + "," + arc_generator.centroid(angle_data[d])[1];
          //内环的中心点
          str += "L" + arc_label.centroid(angle_data[d])[0] + "," + arc_label.centroid(angle_data[d])[1]
          Pie.append("path")
            .attr('class', 'line')
            .attr("d", str)
            .attr("stroke", colors[i])
          i++;

        }

      }

      line_label(angle_data(data))


      Pie.selectAll('text')
        .data(angle_data(data))
        .enter()
        .append('text')
        .attr("text-anchor", "middle")
        .text(function (d) {
          console.log(d);
          return d.data.education + d.data.percentage;
        })
        .style('fill', (d, i) => {
          return colors[i]
        })
        .style('text-decoration',"underline")
        .attr('transform', function (d, i) {
          return "translate(" + arc_label.centroid(d) + ")"
        })


    })


  </script>

</body>

</html>